<?php

	// +----------------------------------------------------------------------
	// | 店铺管理
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace app\controller\store\admin;

	use app\event\file\Attachment as AttachmentEvent;
    use app\model\pos\Pos as PosModel;
    use app\model\store\Store as StoreModel;
	use app\event\store\Store as StoreEvent;
	use app\event\store\User as UserEvent;
	use app\model\store\StoreGrade as StoreGradeModel;
	use app\model\store\Template as TemplateModel;
    use app\model\ucenter\User as UserModel;
    use think\facade\Config;
	use yicmf\builder\Edit;
	use yicmf\builder\Table;

	class Store extends Common
	{
		protected function initialize()
		{
			parent::initialize();
		}

		public function _filter()
		{
			return [];
		}

		/**
		 * 商品评论
		 * @return mixed|string
		 * @access public
		 * @author 微尘 <yicmf@qq.com>
		 */
		public function index()
		{
			// ID 商户编号 商户名称 联系人 联系电话  支付公司  状态 合伙人 入网时间 序列号
            //状态：正常 审核失败 注销 等

			$builder = new Table();
			$builder->model(StoreModel::class)
				->where($this->_filter())
				->order('id DESC')
//				->suggest('超级管理员可以通过点击店铺昵称，直接登录商家后台')
				->searchText('nickname', '商家昵称', '商家昵称')
//				             ->buttonUpdate('update','同步商户信息')
				//             ->searchSelect('status', '状态',$statusOptions)
				->keyId()
//				->keyHidden('code')
//				->keyLink('nickname', '店铺昵称', '/store/{{d.code}}', '_block')
				->keyText('store_sn', '商户编号')
				->keyText('nickname', '店铺名')
                ->keyMap('channel_id', '支付公司',PosModel::$channel)
				->keyText('user.nickname', '合伙人')
				->keyText('create_time', '入网时间')
				->keyText('trade', '交易额')
//				->keyText('grade.name', '店铺等级')
				->keyText('contacts', '联系人')
				->keyText('mobile', '联系方式');
//				->keyText('order_commission', '手续费')
//				->keyTime('end_time', '到期时间')
//				->keyStatus();
//				->actionUpdate('cost?id={$id}', '续费', [-1, 0, 1])
//				->actionUpdate('credit?id={$id}', '保证金', [-1, 0, 1])
//				->actionUpdate()
//				->actionForbid()
//				->actionRestore();
			return $builder->fetch();
		}


        public function update()
        {
            if ($this->request->isPost()) {
                try {
                    $excel_id = $this->request->param('excel_id', '');
                    $insertAll = [];
                    if ($excel_id) {
                        $info = AttachmentEvent::distinguish($excel_id);
                        if (is_array($info)) {
                            foreach ($info as $index => $item) {
                                if ($index > 0 && strlen($item[8])>3) {
                                    $store = StoreModel::where('store_sn',$item[8])->find();
                                    if ($store)
                                    {
                                        $store['nickname'] = $item[1];
                                        $store['trade_count'] = str_replace(',', '', $item[2]);
                                        $store['trade'] = str_replace(',', '', $item[3]);
                                        if ($item[5])
                                        {
                                            $user = UserModel::where('mobile',$item[5])->find();
                                            if ($user)
                                            {
                                                $store['user_id'] = $user['id'];
                                            }
                                        }
//                                        $store['user_mobile'] = $item[5];
//                                        $store['user_nickname'] = $item[4];
                                        $store->save();
                                    }else{
                                        $insert =[];
                                        $insert['channel_id'] = $this->request->param('channel_id', 0);
                                        $insert['nickname'] = $item[1];
                                        $insert['trade_count'] = str_replace(',', '', $item[2]);
                                        $insert['trade'] = str_replace(',', '', $item[3]);
//                                        $insert['user_mobile'] = $item[5];
//                                        $insert['user_nickname'] = $item[4];
                                        $insert['store_sn'] = $item[8];
                                        $insert['pos_sn'] = $item[8];
                                        if ($item[5])
                                        {
                                            $user = UserModel::where('mobile',$item[5])->find();
                                            if ($user)
                                            {
                                                $insert['user_id'] = $user['id'];
                                            }
                                        }
                                        $insert = StoreModel::create($insert);
                                        $pos = PosModel::where('sn',$item[8])->find();
                                        if ($pos)
                                        {
                                            $pos['store_id'] = $insert['id'];
                                            $pos->save();
                                        }
                                    }

                                }
                            }
                        }
                    }


                    $data['message'] = '已更新';

                    $data['code'] = 0;
                } catch (Exception $e) {
                    $data['code'] = 1;
                    $data['message'] = $e->getMessage();
                }
                if (0 === $data['code']) {
                    $this->_returnSuccess($data['message']);
                } else {
                    $this->_returnError($data['message'], false);
                }
            } else {
                // 同步节点与菜单
                if ($this->request->param('id')) {
                    $group_id = $this->request->param('id');
                    $data = PosModel::where('id', $group_id)->find();
                    if (!$data) {
                        $this->_returnError('POS机不存在');
                    }
                } else {
                    $data = [];
                }
                $builder = new Edit();
                $builder->title('商户同步')
                    ->keyRadio('channel_id', '渠道', PosModel::$channel, '', 0)
                    ->keyAttachment('excel_id', '批量')
                ->data($data)
                    ->buttonSubmit();
                return $builder->fetch();
            }
        }

        /**
		 * 续费
		 * @return mixed|string
		 * @access public
		 * @author 微尘 <yicmf@qq.com>
		 */
		public function cost()
		{
			if ($this->request->isPost()) {
				$event = new StoreEvent();
				$result = $event->cost($this->request->post(), $this->user);
				if (0 == $result['code']) {
					$this->_returnSuccess($result['message'], true);
				} else {
					$this->_returnError($result['message']);
				}
			} else {
				$id = $this->request->get('id');
				// 判断是否为编辑模式
				$isEdit = $id ? true : false;
				if ($isEdit) {
					$data = StoreModel::where('id', $id)->find();
				} else {
					$this->_returnError('没有发现商家');
				}

				$builder = new Edit();
				$builder->title('店铺续费信息')
					->keyLabel('nickname', '店铺名称')
					->keyHidden('commission')
					->keyHidden('mobile')
//					->keyText('mobile','手机号')
					->keyLabel('contacts', '联系人', '')
					->keyLabel('mobile', '联系方式')
					->keyLabel('end_time', '到期时间')
					->keyLabel('user.nickname', '店主昵称', '')
					->keyLabel('user.mobile', '店主手机号')
					->keyNumber('number', '续费数量', '', 1)
					->keyRadio('unit', '续费单位', ['月费', '年费'])
					->keyTextInline('message', '留言')
					->keyTextInline('remark', '备注', '店铺不可见')
					->data($data)
					->explain('月费是31天，年费是372天')
					->explain('当前续费' . Config::get('store.month_fee') . '日元/月，年费' . Config::get('store.year_fee') . '日元')
					->buttonSubmit();
				return $builder->fetch();
			}
		}

		/**
		 * 回复评论
		 * @return mixed|string
		 * @access public
		 * @author 微尘 <yicmf@qq.com>
		 */
		public function credit()
		{
			if ($this->request->isPost()) {
				parent::_update(null, 'credit');
			} else {
				$id = $this->request->get('id');
				// 判断是否为编辑模式
				$isEdit = $id ? true : false;
				if ($isEdit) {
					$data = StoreModel::find($id);
				} else {
					$this->_returnError('没有发现商家');
				}

				$builder = new Edit();
				$builder->title('编辑店铺保证金')
					->keyHidden('commission')
					->keyHidden('mobile')
					->keyLabel('nickname', '店铺名称')
					->keyLabel('user.nickname', '店主昵称')
					->keyLabel('user.mobile', '店主手机号')
					->keyDecimal('credit_deposit', '保证金余额', '减少保证金将会把差额退回店主账户余额')
					->data($data)
					->buttonSubmit('', '保 存')//					->explain('0保证金不能保证用户售后流程完成')
				;
				return $builder->fetch();
			}
		}


		/**
		 * 删除消息
		 */
		public function forbid()
		{
			$message = StoreModel::where('id', $this->request->param('id'))
				->find();
			if ($message) {
				$message['status'] = -1;
				$message->save();
				$this->_returnSuccess( '禁用成功');
			} else {
				$this->_returnSuccess( '禁用失败');
			}
		}
		/**
		 * 删除消息
		 */
		public function restore()
		{
			$message = StoreModel::where('id', $this->request->param('id'))
				->find();
			if ($message) {
				$message['status'] = 1;
				$message->save();
				$this->_returnSuccess( '恢复成功');
			} else {
				$this->_returnSuccess( '恢复失败');
			}
		}
	}
